// MQTT控制器
class MQTTController {
    constructor() {
        this.client = null;
        this.isConnected = false;
        this.messageCallback = null;
        this.reconnectTimer = null;
    }

    // 连接到MQTT服务器
    async connect() {
        try {
            const options = {
                clientId: CONFIG.mqtt.clientId,
                username: CONFIG.mqtt.username,
                password: CONFIG.mqtt.password,
                reconnectPeriod: CONFIG.mqtt.reconnectPeriod,
                connectTimeout: CONFIG.mqtt.connectTimeout,
                clean: true
            };

            const url = `wss://${CONFIG.mqtt.host}:${CONFIG.mqtt.port}${CONFIG.mqtt.path}`;
            
            this.client = mqtt.connect(url, options);

            this.client.on('connect', () => {
                console.log('MQTT连接成功');
                this.isConnected = true;
                this.updateStatus(true);
                this.subscribe();
            });

            this.client.on('message', (topic, message) => {
                console.log('收到MQTT消息:', topic, message.toString());
                this.handleMessage(message.toString());
            });

            this.client.on('error', (error) => {
                console.error('MQTT错误:', error);
                this.updateStatus(false);
                this.showError(CONFIG.errors.mqttConnectionFailed);
            });

            this.client.on('close', () => {
                console.log('MQTT连接关闭');
                this.isConnected = false;
                this.updateStatus(false);
            });

            this.client.on('reconnect', () => {
                console.log('MQTT重新连接中...');
                this.updateStatus(false);
            });

        } catch (error) {
            console.error('MQTT连接失败:', error);
            this.showError(CONFIG.errors.mqttConnectionFailed);
        }
    }

    // 订阅主题
    subscribe() {
        if (this.client && this.isConnected) {
            const topic = CONFIG.device.getTopic();
            this.client.subscribe(topic, (err) => {
                if (err) {
                    console.error('订阅失败:', err);
                } else {
                    console.log('订阅成功:', topic);
                }
            });
        }
    }

    // 处理接收到的消息
    handleMessage(message) {
        try {
            const data = JSON.parse(message);
            
            // 验证消息格式
            if (!this.validateMessage(data)) {
                console.error('无效的消息格式:', data);
                return;
            }

            // 调用回调函数处理消息
            if (this.messageCallback) {
                this.messageCallback(data);
            }

        } catch (error) {
            console.error('消息解析失败:', error);
            this.showError(CONFIG.errors.invalidMessage);
        }
    }

    // 验证消息格式
    validateMessage(data) {
        if (!data || typeof data !== 'object') {
            return false;
        }

        if (!data.type || !Object.values(CONFIG.messageTypes).includes(data.type)) {
            return false;
        }

        // 根据类型验证必要字段
        switch (data.type) {
            case CONFIG.messageTypes.WEBPAGE:
            case CONFIG.messageTypes.IMAGE:
            case CONFIG.messageTypes.VIDEO:
                return !!data.url;
            case CONFIG.messageTypes.TEXT:
                return !!data.content;
            case CONFIG.messageTypes.CLEAR:
                return true;
            default:
                return false;
        }
    }

    // 设置消息处理回调
    onMessage(callback) {
        this.messageCallback = callback;
    }

    // 更新连接状态显示
    updateStatus(connected) {
        const statusIndicator = document.getElementById('mqttStatus');
        const statusText = document.getElementById('statusText');
        
        if (connected) {
            statusIndicator.classList.add('connected');
            statusText.textContent = 'MQTT已连接';
        } else {
            statusIndicator.classList.remove('connected');
            statusText.textContent = 'MQTT连接中...';
        }
    }

    // 显示错误信息
    showError(message) {
        const errorDisplay = document.getElementById('errorDisplay');
        const errorMessage = document.getElementById('errorMessage');
        
        errorMessage.textContent = message;
        errorDisplay.classList.remove('hidden');
        
        // 3秒后自动隐藏错误信息
        setTimeout(() => {
            errorDisplay.classList.add('hidden');
        }, 3000);
    }

    // 断开连接
    disconnect() {
        if (this.client) {
            this.client.end();
            this.client = null;
        }
        this.isConnected = false;
        this.updateStatus(false);
    }

    // 发布消息（用于测试）
    publish(topic, message) {
        if (this.client && this.isConnected) {
            this.client.publish(topic, JSON.stringify(message));
        }
    }
} 